<?php

namespace libs\qoy;

use libs\qoy\Exception\ExceptionInternalServerError;
use libs\qoy\Exception\ExceptionVerify;
use libs\qoy\Exception\ExceptionBadRequest;

/**
 * 路由类
 * 
 */
class Request {

    protected static $headers;
    private static $controller;
    private static $action;
    private static $data;

    /**
     * 初始化路由参数
     * @param array $data   指定处理请求参数
     */
    public static function init($data = null) {



        if (!isset($data) || !is_array($data)) {
            self::$data = $_REQUEST;
        } else {
            self::$data = $data;
        }


        if (function_exists('getallheaders')) {

            self::$headers = getallheaders();
        } else {
            //对没有getallheaders函数做处理
            $headers = array();
            foreach ($_SERVER as $name => $value) {
                if (is_array($value) || substr($name, 0, 5) != 'HTTP_') {
                    continue;
                }
                $headerKey = implode('-', array_map('ucwords', explode('_', strtolower(substr($name, 5)))));
                $headers[$headerKey] = $value;
            }

            self::$headers = $headers;
        }
    }

    /**
     * 解析路由
     * @param str $app_namespace  应用命名空间
     * @param str $defaultAction   默认接口方法
     * @param str $defaultControllerm    默认接口控制器url
     * @param array $data   指定处理请求参数
     * @throws Exception\ExceptionBadRequest
     */
    public static function rum($app_namespace, $defaultAction, $defaultControllerm) {
        
   
        
        if (isset($_SERVER["PATH_INFO"]) && !empty($_SERVER["PATH_INFO"])) {

            //defined('URL_TYPE') || define('URL_TYPE',INPUT_POST); 
            $urlparam = explode(DIRECTORY_SEPARATOR, trim(filter_input(INPUT_SERVER, "PATH_INFO"), DIRECTORY_SEPARATOR));

            self::$controller = $app_namespace . "\\" . implode(array_slice($urlparam, 0, count($urlparam) - 1), "\\");

            if (!class_exists(self::$controller) || !is_subclass_of(self::$controller, BaseController::class)) {
                //throw new ExceptionBadRequest(ExceptionBadRequest::CONTROLLER);
                self::$controller = $app_namespace . "\\" . implode($urlparam, "\\");
                self::$action = $defaultAction;
            } else {
                self::$action = array_pop($urlparam);
                self::$action = empty(self::$action) ? $defaultAction : self::$action;
                self::$action = trim(self::$action);
                return;
            }

        } else {
            //defined('URL_TYPE') || define('URL_TYPE', INPUT_GET);
            $m = isset($_GET["m"]) ? $_GET["m"] : $defaultControllerm;
            $m = trim($m, DIRECTORY_SEPARATOR);
            self::$controller = $app_namespace . "\\" . implode(explode(DIRECTORY_SEPARATOR, $m), "\\");
            self::$action = isset($_GET["a"]) ? $_GET["a"] : $defaultAction;
        }
        
        if (!class_exists(self::$controller) || !is_subclass_of(self::$controller, BaseController::class)) {
            throw new ExceptionBadRequest(ExceptionBadRequest::CONTROLLER,self::$controller);
            
        }
        self::$action=trim(self::$action);    
    }

    /**
     * 读取请求值
     * @param object $key
     * @param object $defined 
     * @return object 
     */
    public static function get($key, $default = null) {
        if (isset(self::$data[$key]) && !empty(self::$data[$key])) {
            return self::$data[$key];
        }
        return $default;
    }

    /**
     * 读取控制器
     * @return str
     */
    public static function getController() {
        return self::$controller;
    }

    /**
     * 读取接口方法
     * @return str
     */
    public static function getAction() {
        return self::$action;
    }

    /**
     * 获取全部接口参数
     * @return array
     */
    public static function getAll() {
        return self::$data;
    }

    /**
     * 获取全部请求头信息
     * @return array
     */
    public static function getHeadersAll() {
        return self::$headers;
    }

    /**
     * 获取请求头信息
     * @return array
     */
    public static function getHeadersVal($key, $default = null) {


        if (isset(self::$headers[$key]) && !empty(self::$headers[$key])) {
            return self::$headers[$key];
        }
        return $default;
    }

    /**
     * 根据规则获取参数
     * 根据提供的参数规则，进行参数创建工作，并返回错误信息
     *
     * @param $rule array('name' => '', 'type' => '', 'defalt' => ...) 参数规则
     *
     * @return mixed
     */
    public static function getByRule($rule) {
        $rs = NULL;
        if (!isset($rule['name'])) {
            throw new ExceptionInternalServerError(ExceptionInternalServerError::MISS_NAME_FOR_RULE); //T('miss name for rule')
        }

        $rs = ValFormatter::format($rule['name'], $rule, self::$data);

        if ($rs === NULL && (isset($rule['require']) && $rule['require'])) {
            throw new ExceptionVerify(ExceptionVerify::KEY_REQUIRE_BUT_MISS, array('name' => $rule['name'])); //T('{name} require, but miss', array('name' => $rule['name']))
        }
        return $rs;
    }
    public static function geturl() {
        return $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    }

}
